import 'package:flutter/widgets.dart';

abstract class BaseFrameAnimationWidget extends StatefulWidget {
  BaseFrameAnimationWidget({
    this.duration,
    this.frameCount,
    this.defaultFrame,
    this.isPlaying,
  });

  final int? duration;
  final int? frameCount;
  final int? defaultFrame;
  final bool? isPlaying;

  /// 需要实现这个方法， 返回每一帧应该构建什么内容
  Widget buildFrame(BuildContext context, int? frame);

  @override
  _BaseFrameAnimationWidgetState createState() => _BaseFrameAnimationWidgetState();
}

class _BaseFrameAnimationWidgetState extends State<BaseFrameAnimationWidget> with SingleTickerProviderStateMixin {
  late AnimationController controller;
  late Animation<int> frameAnimation;
  int? currentFrame;
  bool playing = false;

  void beginAnimation() {
    if (!playing) {
      controller.repeat();
      playing = true;
    }
  }

  void stopAnimation() {
    if (playing) {
      controller.stop();
      playing = false;
    }
  }

  @override
  void initState() {
    super.initState();

    controller =
        AnimationController(duration: Duration(milliseconds: widget.duration! * widget.frameCount!), vsync: this);
    frameAnimation = IntTween(begin: 0, end: widget.frameCount! - 1).animate(controller);
    frameAnimation.addListener(() {
      if (currentFrame != null && currentFrame != frameAnimation.value) {
        setState(() {});
      }
      currentFrame = frameAnimation.value;
    });
  }

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (widget.isPlaying!) {
      beginAnimation();
      return widget.buildFrame(context, frameAnimation.value);
    } else {
      stopAnimation();
      return widget.buildFrame(context, widget.defaultFrame);
    }
  }
}
